<template>
  <div class="content-detail-page">
    <!-- 顶部导航 -->
    <div class="top-navigation">
      <div class="nav-left">
        <el-button @click="goBack" text size="large">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
      
      <div class="nav-center">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索内容..."
            clearable
            @keyup.enter="handleSearch"
            @clear="clearSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">
            搜索
          </el-button>
        </div>
      </div>
      
      <div class="nav-right">
        <div class="content-navigation">
          <el-button 
            @click="navigateContent('previous')" 
            :disabled="!navigation.previous"
            text
            size="large"
          >
            <el-icon><ArrowUp /></el-icon>
            上一个
          </el-button>
          <el-button 
            @click="navigateContent('next')" 
            :disabled="!navigation.next"
            text
            size="large"
          >
            下一个
            <el-icon><ArrowDown /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton animated>
        <template #template>
          <div class="skeleton-layout">
            <div class="skeleton-content">
              <el-skeleton-item variant="image" style="width: 100%; height: 400px;" />
              <el-skeleton-item variant="h1" style="width: 60%; margin-top: 20px;" />
              <el-skeleton-item variant="text" style="width: 80%; margin-top: 10px;" />
            </div>
            <div class="skeleton-sidebar">
              <el-skeleton-item variant="rect" style="width: 100%; height: 300px;" />
            </div>
          </div>
        </template>
      </el-skeleton>
    </div>
    
    <div v-else-if="content" class="content-layout">
      <!-- 左侧内容区域 -->
      <div class="content-main">
        <!-- 媒体内容 -->
        <div class="media-section">
          <div v-if="content.type === 'IMAGE'" class="image-container">
            <img 
              :src="content.fileUrl" 
              :alt="content.title"
              class="content-image"
              @error="handleImageError"
            />
          </div>
          
          <div v-else-if="content.type === 'VIDEO'" class="video-container">
            <video 
              :src="content.fileUrl" 
              controls 
              class="content-video"
              :poster="content.thumbnailUrl"
            >
              您的浏览器不支持视频播放
            </video>
          </div>
          
          <div v-else class="document-container">
            <div class="document-preview">
              <el-icon class="document-icon"><Document /></el-icon>
              <div class="document-info">
                <h3>{{ content.title }}</h3>
                <p>文档文件</p>
                <el-button type="primary" @click="downloadFile">
                  <el-icon><Download /></el-icon>
                  下载文件
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 内容信息 -->
        <div class="content-info">
          <h1 class="content-title">{{ content.title }}</h1>
          
          <!-- 作者信息 -->
          <div class="author-section">
            <div class="author-info">
              <el-avatar :size="40" class="author-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="author-details">
                <div class="author-name">{{ content.authorName || '匿名用户' }}</div>
                <div class="publish-time">{{ formatTime(content.createdAt) }}</div>
              </div>
            </div>
            
            <!-- 关注按钮 -->
            <el-button v-if="!isOwnContent" type="primary" plain>
              关注
            </el-button>
          </div>
          
          <!-- 内容描述 -->
          <div class="content-description">
            <p>{{ content.description }}</p>
          </div>
          
          <!-- 标签 -->
          <div v-if="content.tags" class="content-tags">
            <span 
              v-for="tag in content.tags.split(',')" 
              :key="tag" 
              class="xhs-tag"
              @click="searchTag(tag.trim())"
            >
              {{ tag.trim() }}
            </span>
          </div>
          
          <!-- 内容统计 -->
          <div class="content-stats">
            <div class="stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ content.viewCount || 0 }} 浏览
              </span>
              <span class="stat-item">
                <el-icon><StarFilled /></el-icon>
                {{ content.likeCount || 0 }} 点赞
              </span>
              <span class="stat-item">
                <el-icon><ChatLineRound /></el-icon>
                {{ content.commentCount || 0 }} 评论
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧边栏：操作和评论区域 -->
      <div class="content-sidebar">
        <!-- 操作按钮 -->
        <div class="action-section">
          <div class="main-actions">
            <el-button 
              @click="toggleLike" 
              :type="content.isLiked ? 'primary' : 'default'"
              :loading="likeLoading"
              size="large"
              class="action-btn like-btn"
            >
              <el-icon><StarFilled /></el-icon>
              <span>{{ content.isLiked ? '已点赞' : '点赞' }}</span>
              <span class="count">{{ content.likeCount || 0 }}</span>
            </el-button>
            
            <el-button 
              @click="shareContent"
              size="large"
              class="action-btn"
            >
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>
        
        <!-- 评论区域 -->
        <div class="comments-sidebar">
          <div class="comments-header">
            <h3>评论 ({{ comments.length }})</h3>
          </div>
          
          <!-- 发表评论 -->
          <div v-if="authStore.isLoggedIn" class="comment-form">
            <el-input
              v-model="newComment"
              type="textarea"
              placeholder="写下你的评论..."
              :rows="3"
              maxlength="500"
              show-word-limit
            />
            <div class="comment-actions">
              <el-button 
                type="primary" 
                @click="submitComment"
                :loading="commentLoading"
                :disabled="!newComment.trim()"
                size="small"
              >
                发表评论
              </el-button>
            </div>
          </div>
          
          <div v-else class="login-prompt">
            <p>请先登录后再发表评论</p>
            <el-button type="primary" size="small" @click="$router.push('/login')">
              去登录
            </el-button>
          </div>
          
          <!-- 评论列表 -->
          <div class="comments-list" ref="commentsRef">
            <div 
              v-for="comment in comments" 
              :key="comment.id" 
              class="comment-item"
            >
              <el-avatar :size="32" class="comment-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-author">{{ comment.userName || '匿名用户' }}</span>
                  <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
                </div>
                <div class="comment-text">{{ comment.text }}</div>
              </div>
            </div>
            
            <!-- 加载更多评论 -->
            <div v-if="hasMoreComments" class="load-more-comments">
              <el-button 
                @click="loadMoreComments" 
                :loading="commentsLoading"
                text
                size="small"
              >
                加载更多评论
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 内容不存在 -->
    <div v-else class="not-found">
      <el-empty description="内容不存在或已被删除">
        <el-button type="primary" @click="$router.push('/')">
          返回首页
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { 
  getContentDetail, 
  getContentNavigation,
  toggleLike as toggleLikeApi,
  getComments,
  addComment,
  searchContents
} from '@/api/content'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { 
  ArrowLeft,
  ArrowUp,
  ArrowDown,
  User,
  View,
  StarFilled,
  ChatLineRound,
  Share,
  Document,
  Download,
  Search
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const content = ref(null)
const navigation = ref({ previous: null, next: null })
const comments = ref([])
const loading = ref(true)
const likeLoading = ref(false)
const commentLoading = ref(false)
const commentsLoading = ref(false)
const hasMoreComments = ref(true)
const commentsPage = ref(0)
const newComment = ref('')
const commentsRef = ref()

// 搜索功能
const searchKeyword = ref('')
const searchLoading = ref(false)

const contentId = computed(() => route.params.id)
const isOwnContent = computed(() => {
  return authStore.user && content.value && 
         content.value.authorName === authStore.user.username
})

// 监听路由变化，重新加载内容
watch(() => route.params.id, () => {
  if (route.params.id) {
    loadContent()
  }
})

// 加载内容详情
const loadContent = async () => {
  try {
    loading.value = true
    const [contentRes, navigationRes] = await Promise.all([
      getContentDetail(contentId.value),
      getContentNavigation(contentId.value)
    ])
    
    content.value = contentRes.data
    navigation.value = navigationRes.data || { previous: null, next: null }
    
    // 加载评论
    await loadComments()
  } catch (error) {
    console.error('加载内容失败:', error)
    ElMessage.error('加载内容失败')
  } finally {
    loading.value = false
  }
}

// 内容导航
const navigateContent = (direction) => {
  const targetContent = navigation.value[direction]
  if (targetContent) {
    router.push(`/content/${targetContent.id}`)
  }
}

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  searchLoading.value = true
  try {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value.trim() }
    })
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    searchLoading.value = false
  }
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 搜索标签
const searchTag = (tag) => {
  searchKeyword.value = tag
  handleSearch()
}

// 加载评论
const loadComments = async (page = 0) => {
  try {
    commentsLoading.value = true
    const res = await getComments(contentId.value, {
      page,
      size: 10
    })
    
    if (res.success) {
      const commentData = res.data
      if (page === 0) {
        comments.value = commentData.content || []
      } else {
        comments.value.push(...(commentData.content || []))
      }
      
      hasMoreComments.value = commentData.content && commentData.content.length === 10
      commentsPage.value = page
    } else {
      ElMessage.error(res.message || '加载评论失败')
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败')
  } finally {
    commentsLoading.value = false
  }
}

// 加载更多评论
const loadMoreComments = () => {
  loadComments(commentsPage.value + 1)
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 点赞/取消点赞
const toggleLike = async () => {
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    likeLoading.value = true
    await toggleLikeApi(contentId.value)
    
    content.value.isLiked = !content.value.isLiked
    content.value.likeCount = content.value.isLiked 
      ? (content.value.likeCount || 0) + 1 
      : Math.max((content.value.likeCount || 1) - 1, 0)
    
    ElMessage.success(content.value.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    likeLoading.value = false
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) return
  
  try {
    commentLoading.value = true
    const res = await addComment(contentId.value, {
      text: newComment.value.trim()
    })
    
    if (res.success) {
      newComment.value = ''
      ElMessage.success('评论发表成功')
      
      // 重新加载评论
      await loadComments()
      
      // 更新评论数
      if (content.value) {
        content.value.commentCount = (content.value.commentCount || 0) + 1
      }
    } else {
      ElMessage.error(res.message || '发表评论失败')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  } finally {
    commentLoading.value = false
  }
}

// 分享内容
const shareContent = () => {
  if (navigator.share) {
    navigator.share({
      title: content.value.title,
      text: content.value.description,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
  }
}

// 下载文件
const downloadFile = () => {
  if (content.value.fileUrl) {
    const link = document.createElement('a')
    link.href = content.value.fileUrl
    link.download = content.value.title
    link.click()
  }
}

// 处理图片错误
const handleImageError = (event) => {
  event.target.style.display = 'none'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    return
  }
  
  switch (event.key) {
    case 'ArrowUp':
      event.preventDefault()
      navigateContent('previous')
      break
    case 'ArrowDown':
      event.preventDefault()
      navigateContent('next')
      break
  }
}

onMounted(() => {
  loadContent()
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped lang="scss">
.content-detail-page {
  min-height: 100vh;
  background-color: $bg-light;
}

.top-navigation {
  background-color: $bg-white;
  padding: $spacing-lg;
  margin-bottom: $spacing-lg;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: $shadow-light;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .nav-left {
    flex: 1;
  }
  
  .nav-center {
    flex: 2;
    display: flex;
    justify-content: center;
    
    .search-bar {
      display: flex;
      gap: $spacing-sm;
      max-width: 400px;
      width: 100%;
      
      .el-input {
        flex: 1;
      }
    }
  }
  
  .nav-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    
    .content-navigation {
      display: flex;
      gap: $spacing-sm;
    }
  }
}

.loading-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: $spacing-lg;
  
  .skeleton-layout {
    display: flex;
    gap: $spacing-xl;
    
    .skeleton-content {
      flex: 2;
    }
    
    .skeleton-sidebar {
      flex: 1;
    }
  }
}

.content-layout {
  max-width: 1200px;
  margin: 0 auto;
  padding: $spacing-lg;
  display: flex;
  gap: $spacing-xl;
  align-items: flex-start;
}

.content-main {
  flex: 2;
  background: $bg-white;
  border-radius: $border-radius-large;
  overflow: hidden;
  box-shadow: $shadow-light;
}

.media-section {
  .image-container {
    width: 100%;
    text-align: center;
    
    .content-image {
      max-width: 100%;
      max-height: 600px;
      object-fit: contain;
    }
  }
  
  .video-container {
    width: 100%;
    
    .content-video {
      width: 100%;
      max-height: 600px;
    }
  }
  
  .document-container {
    padding: $spacing-xl;
    text-align: center;
    
    .document-preview {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: $spacing-lg;
      
      .document-icon {
        font-size: 80px;
        color: $text-light;
      }
      
      .document-info {
        h3 {
          color: $text-primary;
          margin-bottom: $spacing-sm;
        }
        
        p {
          color: $text-secondary;
          margin-bottom: $spacing-lg;
        }
      }
    }
  }
}

.content-info {
  padding: $spacing-xl;
  
  .content-title {
    font-size: $font-size-xxl;
    color: $text-primary;
    margin-bottom: $spacing-lg;
    line-height: 1.4;
  }
  
  .author-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    
    .author-info {
      display: flex;
      align-items: center;
      gap: $spacing-md;
      
      .author-avatar {
        border: 1px solid $border-light;
      }
      
      .author-details {
        .author-name {
          font-weight: 600;
          color: $text-primary;
          margin-bottom: $spacing-xs;
        }
        
        .publish-time {
          font-size: $font-size-sm;
          color: $text-light;
        }
      }
    }
  }
  
  .content-description {
    margin-bottom: $spacing-lg;
    
    p {
      font-size: $font-size-md;
      line-height: 1.6;
      color: $text-secondary;
    }
  }
  
  .content-tags {
    margin-bottom: $spacing-lg;
    
    .xhs-tag {
      margin-right: $spacing-sm;
      margin-bottom: $spacing-sm;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background-color: $primary-color;
        color: white;
      }
    }
  }
  
  .content-stats {
    padding-top: $spacing-lg;
    border-top: 1px solid $border-light;
    
    .stats {
      display: flex;
      gap: $spacing-lg;
      
      .stat-item {
        display: flex;
        align-items: center;
        gap: $spacing-xs;
        color: $text-light;
        font-size: $font-size-sm;
        
        .el-icon {
          font-size: $font-size-md;
        }
      }
    }
  }
}

.content-sidebar {
  flex: 1;
  background: $bg-white;
  border-radius: $border-radius-large;
  padding: $spacing-xl;
  box-shadow: $shadow-light;
  height: fit-content;
  position: sticky;
  top: 120px;
}

.action-section {
  margin-bottom: $spacing-xl;
  
  .main-actions {
    display: flex;
    flex-direction: column;
    gap: $spacing-md;
    
    .action-btn {
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: $spacing-sm;
      
      &.like-btn {
        .count {
          background-color: rgba(255, 255, 255, 0.2);
          border-radius: 20px;
          padding: 2px 8px;
          font-size: $font-size-xs;
        }
      }
    }
  }
}

.comments-sidebar {
  .comments-header {
    margin-bottom: $spacing-lg;
    border-bottom: 1px solid $border-light;
    padding-bottom: $spacing-md;
    
    h3 {
      color: $text-primary;
      font-size: $font-size-lg;
    }
  }
  
  .comment-form {
    margin-bottom: $spacing-lg;
    
    .comment-actions {
      margin-top: $spacing-sm;
      text-align: right;
    }
  }
  
  .login-prompt {
    text-align: center;
    padding: $spacing-md;
    background: $bg-light;
    border-radius: $border-radius-medium;
    margin-bottom: $spacing-lg;
    
    p {
      color: $text-secondary;
      margin-bottom: $spacing-sm;
    }
  }
  
  .comments-list {
    max-height: 400px;
    overflow-y: auto;
    
    .comment-item {
      display: flex;
      gap: $spacing-sm;
      margin-bottom: $spacing-md;
      padding: $spacing-sm;
      border-radius: $border-radius-medium;
      transition: background-color 0.3s ease;
      
      &:hover {
        background-color: $bg-light;
      }
      
      .comment-avatar {
        flex-shrink: 0;
        border: 1px solid $border-light;
      }
      
      .comment-content {
        flex: 1;
        
        .comment-header {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
          margin-bottom: $spacing-xs;
          
          .comment-author {
            font-weight: 600;
            color: $text-primary;
            font-size: $font-size-sm;
          }
          
          .comment-time {
            font-size: $font-size-xs;
            color: $text-light;
          }
        }
        
        .comment-text {
          color: $text-secondary;
          line-height: 1.4;
          font-size: $font-size-sm;
        }
      }
    }
    
    .load-more-comments {
      text-align: center;
      margin-top: $spacing-md;
    }
  }
}

.not-found {
  max-width: 800px;
  margin: 0 auto;
  padding: $spacing-xxl;
  text-align: center;
}

// 响应式设计
@media (max-width: $breakpoint-lg) {
  .content-layout {
    flex-direction: column;
    
    .content-main {
      margin-bottom: $spacing-lg;
    }
    
    .content-sidebar {
      position: static;
      width: 100%;
    }
  }
  
  .top-navigation {
    .nav-center {
      .search-bar {
        max-width: 300px;
      }
    }
  }
}

@media (max-width: $breakpoint-md) {
  .content-layout {
    padding: $spacing-md;
  }
  
  .content-info {
    padding: $spacing-lg;
  }
  
  .content-sidebar {
    padding: $spacing-lg;
  }
  
  .top-navigation {
    flex-direction: column;
    gap: $spacing-md;
    
    .nav-left,
    .nav-center,
    .nav-right {
      flex: none;
      width: 100%;
    }
    
    .nav-center {
      .search-bar {
        max-width: none;
      }
    }
    
    .nav-right {
      .content-navigation {
        justify-content: center;
      }
    }
  }
}

@media (max-width: $breakpoint-sm) {
  .content-layout {
    padding: $spacing-sm;
  }
  
  .content-info {
    padding: $spacing-md;
    
    .content-title {
      font-size: $font-size-xl;
    }
  }
  
  .content-sidebar {
    padding: $spacing-md;
  }
  
  .author-section {
    flex-direction: column;
    gap: $spacing-sm;
    align-items: stretch;
  }
  
  .content-stats .stats {
    justify-content: space-around;
  }
  
  .action-section .main-actions {
    flex-direction: row;
    
    .action-btn {
      height: 40px;
      font-size: $font-size-sm;
    }
  }
}
</style> 